package com.food.restaurantpro.adapters;

import java.util.ArrayList;

import org.w3c.dom.Document;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.food.restaurantpro.R;
import com.food.restaurantpro.RestaurantApp;
import com.food.restaurantpro.objects.Place;
import com.food.restaurantpro.utils.GMapV2Direction;
import com.food.restaurantpro.utils.Prefs;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

public class PlacesAdapter extends ArrayAdapter<Place> {
	private Activity mContext;
	public ArrayList<Place> mPlaceList = new ArrayList<Place>();
	private LayoutInflater inflater;
	private GMapV2Direction mapDirection;
	PolylineOptions redLine;
	//dung cho remove polyline
	private Polyline mPolyline;
	GoogleMap googleMap;
	private Prefs mPrefs;
	

	public PlacesAdapter(Activity context, ArrayList<Place> placeList, GoogleMap map) {
		super(context, R.layout.lv_item_place, R.id.tvRestaurantName, placeList);
		mPrefs = new Prefs(RestaurantApp.CURRENT_CONTEXT);
		googleMap = map;
		this.mContext = context;
		this.mPlaceList = placeList;
		inflater = LayoutInflater.from(mContext);
		mapDirection = new GMapV2Direction();
		
	}

	@Override
	public int getCount() {
		return mPlaceList.size();
	}

	@Override
	public Place getItem(int position) {
		return mPlaceList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	//
	private static class PlaceHolder {
		public TextView tvLocation;
		public TextView tvRestaurantName;
		public Button btnDrivingDirections;
		public TextView tvAddress;
		public TextView tvTime;
		public TextView tvPhone;
		public Button btnPhone;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View listView = convertView;
		PlaceHolder holder = null;
		if (convertView == null) {
			holder = new PlaceHolder();
			listView = inflater.inflate(R.layout.lv_item_place, null);
			holder.tvLocation = (TextView) listView.findViewById(R.id.tvLocation);
			holder.tvRestaurantName = (TextView) listView
					.findViewById(R.id.tvRestaurantName);
			holder.btnDrivingDirections = (Button) listView.findViewById(R.id.btnDrivingDirections);
			holder.tvAddress = (TextView) listView.findViewById(R.id.tvAddress);
			holder.tvTime = (TextView) listView.findViewById(R.id.tvTime);
			holder.tvPhone = (TextView) listView.findViewById(R.id.tvPhone);
			holder.btnPhone = (Button) listView.findViewById(R.id.btnPhone);
			listView.setTag(holder);

		} else {
			listView = convertView;
			holder = (PlaceHolder) listView.getTag();
		}
		final Place place = mPlaceList.get(position);
		if(position == 0) {
			//thay doi icon cho nha hang chinh
			holder.tvLocation.setBackgroundResource(R.drawable.place_home);
			holder.tvLocation.setText("");
		} else {
			holder.tvLocation.setBackgroundResource(R.drawable.marker_icon);
			int location = position + 1;
			holder.tvLocation.setText(location + "");
		}
		holder.tvRestaurantName.setText(place.getPlaceName());
		holder.tvAddress.setText(place.getPlaceAddress());
		holder.tvTime.setText(place.getPlaceOpen() + " - " + place.getPlaceClose());
		holder.tvPhone.setText(place.getPlacePhone());

		holder.btnDrivingDirections.setTag(place);
		holder.btnDrivingDirections.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Place pl = (Place) v.getTag();
				drawDirection(pl);
			}
		});
		
		holder.btnPhone.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				makeACall(place.getPlacePhone());
			}
		});
		return listView;
	}
	
	private void drawDirection(Place place) {
		showProcessDialog();
		double from_lat = Double.parseDouble(mPrefs.getStringValue("0", Prefs.KEY_MY_LAT));
		double from_long = Double.parseDouble(mPrefs.getStringValue("0", Prefs.KEY_MY_LONG));
		final LatLng fromPosition = new LatLng(from_lat, from_long);
		
		double to_lat = Double.parseDouble(place.getPlaceLat());
		double to_long = Double.parseDouble(place.getPlaceLong());
		final LatLng toPosition = new LatLng(to_lat, to_long);
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Document doc = mapDirection.getDocument(fromPosition, toPosition,
						GMapV2Direction.MODE_DRIVING);
				ArrayList<LatLng> directionPoint = mapDirection.getDirection(doc);
				redLine = new PolylineOptions().width(3).color(
						Color.RED);

				for (int i = 0; i < directionPoint.size(); i++) {
					redLine.add(directionPoint.get(i));
				}
				mContext.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if(mPolyline != null) {
							mPolyline.remove();
						}
						mPolyline = googleMap.addPolyline(redLine);
						googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
						hideProcessDialog();
					}
				});
				
			}
		}).start();
	}

	//---------------------makeACall----------------	
	private void makeACall(String phoneNumber) {
		if (!phoneNumber.trim().equalsIgnoreCase("")) {
			if (checkSimCardState(mContext)) {
				Intent callIntent = new Intent(Intent.ACTION_DIAL);
				callIntent.setData(Uri.parse("tel:" + phoneNumber));
				mContext.startActivity(callIntent);
			} else {
				Toast.makeText(mContext, mContext.getText(R.string.simcard_notavailable), 1000).show();
			}
		} else {
			Toast.makeText(mContext, mContext.getText(R.string.phone_notavailable), 1000).show();
		}
	
	}
	
	public boolean checkSimCardState(Context context) {
		TelephonyManager telMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		int simState = telMgr.getSimState();
		boolean isSim=false;
		switch (simState) {
		case TelephonyManager.SIM_STATE_ABSENT:
			
			isSim=false;
			break;
		case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
			isSim=false;
			break;
		case TelephonyManager.SIM_STATE_PIN_REQUIRED:
			isSim=false;
			break;
		case TelephonyManager.SIM_STATE_PUK_REQUIRED:
			isSim=false;
			break;
		case TelephonyManager.SIM_STATE_READY:
			isSim=true;
			break;
		case TelephonyManager.SIM_STATE_UNKNOWN:
			isSim=false;
			break;
		}
		return isSim;
		
	}
	
	public void clearMemoryCache() {
		hideProcessDialog();
		if (mPlaceList != null) {
			mPlaceList.clear();
			mPlaceList = null;
		}
		inflater = null;
		if(mPolyline != null) {
			mPolyline.remove();
		}
	}
	
	private ProgressDialog _waitingDialog;
	private void showProcessDialog() {
		if (_waitingDialog == null || !_waitingDialog.isShowing()) {
			_waitingDialog = new ProgressDialog(mContext);
			_waitingDialog.setMessage(mContext.getString(R.string.processing));
			_waitingDialog.setCancelable(false);
			_waitingDialog.show();
		}
	}

	//Ham nay phai duoc goi trong onDestroy
	//Vi co truong hop dang request thi destroy activity
	//dialog se ko duoc dong neu ko dat ham nay trong onDestroy
	private void hideProcessDialog() {
		if (_waitingDialog != null && _waitingDialog.isShowing()) {
			_waitingDialog.dismiss();
		}
	}
}
